"""
菜单模型
"""
from datetime import datetime
from app.extensions import db


class Menu(db.Model):
    """菜单模型"""
    __tablename__ = 'menu'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    path = db.Column(db.String(200))
    icon = db.Column(db.String(50))
    parent_id = db.Column(db.Integer, db.ForeignKey('menu.id'), nullable=True)
    sort_order = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 自引用关系
    children = db.relationship('Menu', backref=db.backref('parent', remote_side=[id]))
    
    def to_dict(self, include_children=True):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'path': self.path,
            'icon': self.icon,
            'parent_id': self.parent_id,
            'sort_order': self.sort_order,
            'is_active': self.is_active,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        if include_children:
            result['children'] = [child.to_dict(False) for child in self.children if child.is_active]
            
        return result


# 角色菜单关联表
role_menu = db.Table('role_menu',
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True),
    db.Column('menu_id', db.Integer, db.ForeignKey('menu.id'), primary_key=True)
)